package com.iman.fetion.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

public class FetionServer {

	private static final int PORT = 7601;

	public void startUp() throws IOException {
		ByteBuffer.setUseDirectBuffers(false);
		ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

		IoAcceptor acceptor = new SocketAcceptor();
		TextLineCodecFactory factory = new TextLineCodecFactory(Charset
				.forName("UTF-8"));
		factory.setDecoderMaxLineLength(Integer.MAX_VALUE);
		factory.setEncoderMaxLineLength(Integer.MAX_VALUE);

		SocketAcceptorConfig cfg = new SocketAcceptorConfig();
		cfg.getFilterChain().addLast("logger", new FetionLoggingFilter());
		cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
		cfg.getFilterChain().addLast("threadPool",
				new ExecutorFilter(Executors.newCachedThreadPool()));
		acceptor.bind(new InetSocketAddress(PORT), new FetionServerHandler(),
				cfg);
		System.out.println("MINA Fetion server started.");
	}

}
